function [msacloc sac_thres] = EL1k_microsacdetect(tspeed, MULT, deltatime, thresh)
% 
% [msacloc sac_thres] = EL1k_microsacdetect(tspeed, MULT, deltatime, [thresh])
% tspeed = speed during trial
% MULT = std multiplyer
% deltatime = mean(diff(ttime)) or 'time step' : (usu 2ms)
% thresh = force a fixed threshold (not suggested)
%

if nargin==0
	help(mfilename)
	return
end
if nargin==3
thresh=-1;
end
fix_noise=tspeed(tspeed<50); % most people use a fixed 50dps for saccade onset. here i remove all speeds over 60dps ...
if thresh >= 0
    sac_thres=thresh;
else
   sac_thres=mean(fix_noise)+std(fix_noise)*MULT; 
	%sac_thres=max([20 mean(fix_noise)+(MULT*std(fix_noise))]); % and find
	%the mean and 3std to create a variable threshold to compensate for different noise levels
end

s=[0;tspeed;0];
d=[0;diff(s>=sac_thres);0]; % speed goes above threshold
e=[find(d==1) find(d==-1)-1];
l=e(:,2)-e(:,1);
e(l<5/deltatime,:)=[];% saccades must last longer than 10 ms

sacloc=[];
n2=size(e,1);
if n2 > 0
    peak=zeros(n2,1);
    for i=1:n2
        peak(i)=max(s(e(i,1):e(i,2)));
    end
    fsac= peak>sac_thres*2; % faster than ???	
    if ~isempty(fsac)
        sacloc=e(fsac,:)-1;
    end
else
    sac_thres=-9999;
    sacloc=[];
end
[sacloc2 ] = EL1k_sacdetect(tspeed, MULT, deltatime, sac_thres);
[~, i]=SETDIFF(round(sacloc(:,1)/5),round(sacloc2(:,1)/5));
msacloc=sacloc(i,:);